//
//  ALComposeViewController.swift
//  Swift01
//
//  Created by Miaoyang on 16/4/19.
//  Copyright © 2016年 Miaoyang. All rights reserved.
//

import UIKit

class ALComposeViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        
        prepareUI()
        
        // 监听键盘frame的改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ALComposeViewController.willChangeFrame(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
       
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        textView.becomeFirstResponder()
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
     
 
    @objc private func willChangeFrame(notification: NSNotification) {
        //        HMPrint("notification: \(notification)")
        // 键盘frame的值
        let frame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        let y = -(UIScreen.mainScreen().bounds.height - frame.origin.y)
        
        // 动画
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(y)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    
    private func prepareUI() {
        setupNavigationBar()
        
        setupTextView()
        setupToolBar()
    }
    
    /// 设置textView
    private func setupTextView() {
        // 1.添加控件
        view.addSubview(textView)
        
        // 2.添加约束
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view)
        }
        
              self.automaticallyAdjustsScrollViewInsets = true
    }
    
    /// 设置toolBar
    private func setupToolBar() {
        // 添加控件
        view.addSubview(toolBar)
        
        // 添加约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        // 每个item对应的图片名称
        let itemSettings = [
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_add_background", "action": "add"]
        ]
        
        var items = [UIBarButtonItem]()
        var index = 0
        // 遍历数组获取每个item的信息
        for dict in itemSettings {
            // 获取图片名称
            let iamgeName = dict["imageName"]!
            
            // 获取点击事件的名称
            let action = dict["action"]!
            
            // 创建UIBarButtonItem, 里面包一个按钮
            let item = UIBarButtonItem(imageName: iamgeName, target: self, action: Selector(action))
            items.append(item)
            
            let button = item.customView as! UIButton
            button.tag = index
            
            // 添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
            index++
        }
        
        // 删除最后一个弹簧
        items.removeLast()
        
        toolBar.items = items
    }
    
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(ALComposeViewController.close))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(ALComposeViewController.sendStatus))
        
        // 右边按钮不可用
        navigationItem.rightBarButtonItem?.enabled = false
        
        setupTitleView()
    }
    
    /// 设置TitleView
    private func setupTitleView() {
        //        navigationItem.titleView
        let prefix = "发微博"
        if let name = ALUserAccountViewModel.sharedInstance.userAccount?.screen_name {
            // 有名字 \n 换行
            let title = prefix + "\n" + name
            
            // 创建label
            let titleLabel = UILabel()
            titleLabel.numberOfLines = 0
            titleLabel.textAlignment = NSTextAlignment.Center
            titleLabel.textColor = UIColor.blackColor()
            titleLabel.font = UIFont.systemFontOfSize(ALWelcomeLabelFontSize)
            
            // 使用属性文本
            let attrStringM = NSMutableAttributedString(string: title)
            
            let range = (title as NSString).rangeOfString(name)
            // 添加属性
            // NSForegroundColorAttributeName: 文字的前景颜色
            attrStringM.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: range)
            attrStringM.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: range)
            
            titleLabel.attributedText = attrStringM
            
            // label的size会根据label里面的文本内容自己计算
            titleLabel.sizeToFit()
            
            navigationItem.titleView = titleLabel
        } else {
            // 没有名字
            navigationItem.title = prefix
        }
    }
    
    // MARK: - 按钮点击事件
    @objc private func picture() {
        print("图片")
    }
    
    @objc private func trend() {
        print("#")
    }
    
    
    @objc private func mention() {
        print("@")
    }
    
    
    @objc private func emoticon() {
        print("表情")
    }
    
    
    @objc private func add() {
        print("加号")
    }
    
    @objc private func didClickItem(button: UIButton) {
        switch button.tag {
        case 0:
            print("图片")
        case 1:
            print("#")
        case 2:
            print("@")
        case 3:
            print("表情")
        case 4:
            print("加号")
        default:
            print("没有按钮")
        }
    }
    
    @objc private func close() {
        // textView取消第一相应者,键盘就会退下
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func sendStatus() {
        ALPrint("")
    }
    
    // MARK: - 懒加载
    /// toolBar
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    /// textView
    private lazy var textView: ALPlaceholderTextView = {
        let tv = ALPlaceholderTextView()
        
        // 设置
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.blackColor()
        
        //        tv.text = "分享新鲜事......"
        
        // 设置占位文本
        tv.placeholder = "我是占位文本"
        
        // 监听textView文字的改变
        tv.delegate = self
        
        // 垂直弹簧效果
        tv.alwaysBounceVertical = true
        
        // 当拖拽textView就会关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        return tv
    }()
}

extension ALComposeViewController: UITextViewDelegate {
    // 文字改变
    func textViewDidChange(textView: UITextView) {
        // 设置导航栏右边按钮的可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
